package com.xy.common.config.druid;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.xy.common.config.druid.properties.DruidProperties;
import com.xy.common.datasource.DynamicDataSource;
import com.xy.common.enums.DataSourceType;
import com.xy.common.utils.spring.SpringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
 * druid 配置多数据源
 * 
 *  切换其他数据源，改 当前文件、DataSourceType、DataSource 配置
 */
@Configuration
public class DruidConfig
{
    @Bean(name = "zqbDataSource")
    @ConfigurationProperties("spring.datasource.druid.zqb")
    public DataSource zqbDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "jmDataSource")
    @ConfigurationProperties("spring.datasource.druid.jm")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.jm", name = "enabled", havingValue = "true")
    public DataSource jmDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource zqbDataSource)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.ZQB.name(), zqbDataSource);
        setDataSource(targetDataSources, DataSourceType.JM.name(), "jmDataSource");
        return new DynamicDataSource(zqbDataSource, targetDataSources);
    }

    /**
     * 设置数据源
     * 
     * @param targetDataSources 备选数据源集合
     * @param sourceName 数据源名称
     * @param beanName bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName)
    {
        try
        {
            DataSource dataSource = SpringUtils.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
        }
        catch (Exception e)
        {
        }
    }
}
